import { defineStore } from "pinia";

const useDeviceStore = defineStore("device", () => {
  // 窗口尺寸状态
  const windowWidth = ref(window.innerWidth);
  const windowHeight = ref(window.innerHeight);

  // 设备类型状态
  const deviceType = ref("desktop");

  // 计算属性：设备类型判断
  const isMobile = computed(() => deviceType.value === "mobile");
  const isTablet = computed(() => deviceType.value === "tablet");
  const isDesktop = computed(() => deviceType.value === "desktop");

  // 更新窗口尺寸
  const updateWindowSize = () => {
    windowWidth.value = window.innerWidth;
    windowHeight.value = window.innerHeight;
    updateDeviceType();
  };

  // 更新设备类型
  const updateDeviceType = () => {
    if (windowWidth.value < 768) {
      deviceType.value = "mobile";
    } else if (windowWidth.value <= 1024) {
      deviceType.value = "tablet";
    } else {
      deviceType.value = "desktop";
    }
  };

  // 窗口监听处理函数
  const handleResize = () => {
    updateWindowSize();
  };

  // 初始化窗口监听
  const initWindowListener = () => {
    updateWindowSize(); // 初始化
    window.addEventListener("resize", handleResize);
  };

  // 移除窗口监听
  const removeWindowListener = () => {
    window.removeEventListener("resize", handleResize);
  };

  return {
    // 状态
    windowWidth,
    windowHeight,
    deviceType,

    // 计算属性
    isMobile,
    isTablet,
    isDesktop,

    // 方法
    initWindowListener,
    removeWindowListener,
    updateWindowSize,
  };
});

export default useDeviceStore;
